package zuo.biao.library.util;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.nio.charset.Charset;

/**
 * 生成md5
 */
public class ECodeMD5 {

    static final String[] HEXS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
    // 标准的幻数
    private static final long ACC = 0x67452301L;
    private static final long BCC = 0xefcdab89L;
    private static final long CCC = 0x98badcfeL;
    private static final long DCC = 0x10325476L;

    // 下面这些S11-S44实际上是一个4*4的矩阵，在四轮循环运算中用到
    static final int SA11 = 7;
    static final int SB12 = 12;
    static final int SC13 = 17;
    static final int SD14 = 22;

    static final int SA21 = 5;
    static final int SB22 = 9;
    static final int SC23 = 14;
    static final int SD24 = 20;

    static final int SA31 = 4;
    static final int SB32 = 11;
    static final int SC33 = 16;
    static final int SD34 = 23;

    static final int SA41 = 6;
    static final int SB42 = 10;
    static final int SC43 = 15;
    static final int SD44 = 21;

    // java不支持无符号的基本数据（unsigned）
    private long[] result = {ACC, BCC, CCC, DCC}; // 存储hash结果，共4×32=128位，初始化值为（幻数的级联）

    /**
     * 加密
     * @param inputStr 字符串
     * @return 加密后的字符串
     */
    public String digest(String inputStr) {
        byte[] inputBytes = inputStr.getBytes(Charset.defaultCharset());
        int byteLen = inputBytes.length; // 长度（字节）
        int groupCount = 0; // 完整分组的个数
        groupCount = byteLen / 64; // 每组512位（64字节）
        long[] groups = null; // 每个小组(64字节)再细分后的16个小组(4字节)

        // 处理每一个完整 分组
        for (int step = 0; step < groupCount; step++) {
            groups = divGroup(inputBytes, step * 64);
            trans(groups); // 处理分组，核心算法
        }

        // 处理完整分组后的尾巴
        int rest = byteLen % 64; // 512位分组后的余数
        byte[] tempBytes = new byte[64];
        if (rest <= 56) {
            for (int i = 0; i < rest; i++) {
                tempBytes[i] = inputBytes[byteLen - rest + i];
            }
            if (rest < 56) {
                tempBytes[rest] = (byte) (1 << 7);
                for (int i = 1; i < 56 - rest; i++){
                    tempBytes[rest + i] = 0;
                }
            }
            long len = (long) (byteLen << 3);
            for (int i = 0; i < 8; i++) {
                tempBytes[56 + i] = (byte) (len & 0xFFL);
                len = len >> 8;
            }
            groups = divGroup(tempBytes, 0);
            trans(groups); // 处理分组
        } else {
            for (int i = 0; i < rest; i++) {
                tempBytes[i] = inputBytes[byteLen - rest + i];
            }
            tempBytes[rest] = (byte) (1 << 7);
            for (int i = rest + 1; i < 64; i++) {
                tempBytes[i] = 0;
            }
            groups = divGroup(tempBytes, 0);
            trans(groups); // 处理分组

            for (int i = 0; i < 56; i++) {
                tempBytes[i] = 0;
            }
            long len = (long) (byteLen << 3);
            for (int i = 0; i < 8; i++) {
                tempBytes[56 + i] = (byte) (len & 0xFFL);
                len = len >> 8;
            }
            groups = divGroup(tempBytes, 0);
            trans(groups); // 处理分组
        }

        // 将Hash值转换成十六进制的字符串
        String resStr = "";
        long temp = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                temp = result[i] & 0x0FL;
                String a = HEXS[(int) (temp)];
                result[i] = result[i] >> 4;
                temp = result[i] & 0x0FL;
                resStr += HEXS[(int) (temp)] + a;
                result[i] = result[i] >> 4;
            }
        }
        return resStr;
    }

    /**
     * 从inputBytes的index开始取512位，作为新的分组
     * 将每一个512位的分组再细分成16个小组，每个小组64位（8个字节）
     * @param inputBytes i
     * @param index i
     * @return long
     */
    private static long[] divGroup(byte[] inputBytes, int index) {
        long[] temp = new long[16];
        for (int i = 0; i < 16; i++) {
            temp[i] =
                    b2iu(inputBytes[4 * i + index])
                            | (b2iu(inputBytes[4 * i + 1 + index])) << 8
                            | (b2iu(inputBytes[4 * i + 2 + index])) << 16
                            | (b2iu(inputBytes[4 * i + 3 + index])) << 24;
        }
        return temp;
    }

    /**
     * 这时不存在符号位（符号位存储不再是代表正负），所以需要处理一下
     * @param b2iu b
     * @return long
     */
    public static long b2iu(byte b2iu) {
        return b2iu < 0 ? b2iu & 0x7F + 128 : b2iu;
    }

    /**
     * 主要的操作，四轮循环
     * @param groups g
     */
    private void trans(long[] groups) {
        long ace = result[0];
        long bce = result[1];
        long cce = result[2];
        long dce = result[3];
        /* 第一轮 */
        ace = aFF(ace, bce, cce, dce, groups[0], SA11, 0xd76aa478L); /* 1 */
        dce = aFF(dce, ace, bce, cce, groups[1], SB12, 0xe8c7b756L); /* 2 */
        cce = aFF(cce, dce, ace, bce, groups[2], SC13, 0x242070dbL); /* 3 */
        bce = aFF(bce, cce, dce, ace, groups[3], SD14, 0xc1bdceeeL); /* 4 */
        ace = aFF(ace, bce, cce, dce, groups[4], SA11, 0xf57c0fafL); /* 5 */
        dce = aFF(dce, ace, bce, cce, groups[5], SB12, 0x4787c62aL); /* 6 */
        cce = aFF(cce, dce, ace, bce, groups[6], SC13, 0xa8304613L); /* 7 */
        bce = aFF(bce, cce, dce, ace, groups[7], SD14, 0xfd469501L); /* 8 */
        ace = aFF(ace, bce, cce, dce, groups[8], SA11, 0x698098d8L); /* 9 */
        dce = aFF(dce, ace, bce, cce, groups[9], SB12, 0x8b44f7afL); /* 10 */
        cce = aFF(cce, dce, ace, bce, groups[10], SC13, 0xffff5bb1L); /* 11 */
        bce = aFF(bce, cce, dce, ace, groups[11], SD14, 0x895cd7beL); /* 12 */
        ace = aFF(ace, bce, cce, dce, groups[12], SA11, 0x6b901122L); /* 13 */
        dce = aFF(dce, ace, bce, cce, groups[13], SB12, 0xfd987193L); /* 14 */
        cce = aFF(cce, dce, ace, bce, groups[14], SC13, 0xa679438eL); /* 15 */
        bce = aFF(bce, cce, dce, ace, groups[15], SD14, 0x49b40821L); /* 16 */

        /* 第二轮 */
        ace = bGG(ace, bce, cce, dce, groups[1], SA21, 0xf61e2562L); /* 17 */
        dce = bGG(dce, ace, bce, cce, groups[6], SB22, 0xc040b340L); /* 18 */
        cce = bGG(cce, dce, ace, bce, groups[11], SC23, 0x265e5a51L); /* 19 */
        bce = bGG(bce, cce, dce, ace, groups[0], SD24, 0xe9b6c7aaL); /* 20 */
        ace = bGG(ace, bce, cce, dce, groups[5], SA21, 0xd62f105dL); /* 21 */
        dce = bGG(dce, ace, bce, cce, groups[10], SB22, 0x2441453L); /* 22 */
        cce = bGG(cce, dce, ace, bce, groups[15], SC23, 0xd8a1e681L); /* 23 */
        bce = bGG(bce, cce, dce, ace, groups[4], SD24, 0xe7d3fbc8L); /* 24 */
        ace = bGG(ace, bce, cce, dce, groups[9], SA21, 0x21e1cde6L); /* 25 */
        dce = bGG(dce, ace, bce, cce, groups[14], SB22, 0xc33707d6L); /* 26 */
        cce = bGG(cce, dce, ace, bce, groups[3], SC23, 0xf4d50d87L); /* 27 */
        bce = bGG(bce, cce, dce, ace, groups[8], SD24, 0x455a14edL); /* 28 */
        ace = bGG(ace, bce, cce, dce, groups[13], SA21, 0xa9e3e905L); /* 29 */
        dce = bGG(dce, ace, bce, cce, groups[2], SB22, 0xfcefa3f8L); /* 30 */
        cce = bGG(cce, dce, ace, bce, groups[7], SC23, 0x676f02d9L); /* 31 */
        bce = bGG(bce, cce, dce, ace, groups[12], SD24, 0x8d2a4c8aL); /* 32 */

        /* 第三轮 */
        ace = cHH(ace, bce, cce, dce, groups[5], SA31, 0xfffa3942L); /* 33 */
        dce = cHH(dce, ace, bce, cce, groups[8], SB32, 0x8771f681L); /* 34 */
        cce = cHH(cce, dce, ace, bce, groups[11], SC33, 0x6d9d6122L); /* 35 */
        bce = cHH(bce, cce, dce, ace, groups[14], SD34, 0xfde5380cL); /* 36 */
        ace = cHH(ace, bce, cce, dce, groups[1], SA31, 0xa4beea44L); /* 37 */
        dce = cHH(dce, ace, bce, cce, groups[4], SB32, 0x4bdecfa9L); /* 38 */
        cce = cHH(cce, dce, ace, bce, groups[7], SC33, 0xf6bb4b60L); /* 39 */
        bce = cHH(bce, cce, dce, ace, groups[10], SD34, 0xbebfbc70L); /* 40 */
        ace = cHH(ace, bce, cce, dce, groups[13], SA31, 0x289b7ec6L); /* 41 */
        dce = cHH(dce, ace, bce, cce, groups[0], SB32, 0xeaa127faL); /* 42 */
        cce = cHH(cce, dce, ace, bce, groups[3], SC33, 0xd4ef3085L); /* 43 */
        bce = cHH(bce, cce, dce, ace, groups[6], SD34, 0x4881d05L); /* 44 */
        ace = cHH(ace, bce, cce, dce, groups[9], SA31, 0xd9d4d039L); /* 45 */
        dce = cHH(dce, ace, bce, cce, groups[12], SB32, 0xe6db99e5L); /* 46 */
        cce = cHH(cce, dce, ace, bce, groups[15], SC33, 0x1fa27cf8L); /* 47 */
        bce = cHH(bce, cce, dce, ace, groups[2], SD34, 0xc4ac5665L); /* 48 */

        /* 第四轮 */
        ace = dII(ace, bce, cce, dce, groups[0], SA41, 0xf4292244L); /* 49 */
        dce = dII(dce, ace, bce, cce, groups[7], SB42, 0x432aff97L); /* 50 */
        cce = dII(cce, dce, ace, bce, groups[14], SC43, 0xab9423a7L); /* 51 */
        bce = dII(bce, cce, dce, ace, groups[5], SD44, 0xfc93a039L); /* 52 */
        ace = dII(ace, bce, cce, dce, groups[12], SA41, 0x655b59c3L); /* 53 */
        dce = dII(dce, ace, bce, cce, groups[3], SB42, 0x8f0ccc92L); /* 54 */
        cce = dII(cce, dce, ace, bce, groups[10], SC43, 0xffeff47dL); /* 55 */
        bce = dII(bce, cce, dce, ace, groups[1], SD44, 0x85845dd1L); /* 56 */
        ace = dII(ace, bce, cce, dce, groups[8], SA41, 0x6fa87e4fL); /* 57 */
        dce = dII(dce, ace, bce, cce, groups[15], SB42, 0xfe2ce6e0L); /* 58 */
        cce = dII(cce, dce, ace, bce, groups[6], SC43, 0xa3014314L); /* 59 */
        bce = dII(bce, cce, dce, ace, groups[13], SD44, 0x4e0811a1L); /* 60 */
        ace = dII(ace, bce, cce, dce, groups[4], SA41, 0xf7537e82L); /* 61 */
        dce = dII(dce, ace, bce, cce, groups[11], SB42, 0xbd3af235L); /* 62 */
        cce = dII(cce, dce, ace, bce, groups[2], SC43, 0x2ad7d2bbL); /* 63 */
        bce = dII(bce, cce, dce, ace, groups[9], SD44, 0xeb86d391L); /* 64 */

        /* 加入到之前计算的结果当中 */
        result[0] += ace;
        result[1] += bce;
        result[2] += cce;
        result[3] += dce;
        result[0] = result[0] & 0xFFFFFFFFL;
        result[1] = result[1] & 0xFFFFFFFFL;
        result[2] = result[2] & 0xFFFFFFFFL;
        result[3] = result[3] & 0xFFFFFFFFL;
    }

    /**
     * 下面是处理要用到的线性函数
     * @param xal xal
     * @param yal yal
     * @param zal zal
     * @return long
     */
    private static long aF(long xal, long yal, long zal) {
        return (xal & yal) | ((~xal) & zal);
    }

    private static long bG(long x, long y, long z) {
        return (x & z) | (y & (~z));
    }

    private static long cH(long x, long y, long z) {
        return x ^ y ^ z;
    }

    private static long dI(long x, long y, long z) {
        return y ^ (x | (~z));
    }

    private static long aFF(long a, long b, long c, long d, long x, long s, long ac) {
        a += (aF(b, c, d) & 0xFFFFFFFFL) + x + ac;
        a = ((a & 0xFFFFFFFFL) << s) | ((a & 0xFFFFFFFFL) >>> (32 - s));
        a += b;
        return (a & 0xFFFFFFFFL);
    }

    private static long bGG(long a, long b, long c, long d, long x, long s, long ac) {
        a += (bG(b, c, d) & 0xFFFFFFFFL) + x + ac;
        a = ((a & 0xFFFFFFFFL) << s) | ((a & 0xFFFFFFFFL) >>> (32 - s));
        a += b;
        return (a & 0xFFFFFFFFL);
    }

    private static long cHH(long a, long b, long c, long d, long x, long s, long ac) {
        a += (cH(b, c, d) & 0xFFFFFFFFL) + x + ac;
        a = ((a & 0xFFFFFFFFL) << s) | ((a & 0xFFFFFFFFL) >>> (32 - s));
        a += b;
        return (a & 0xFFFFFFFFL);
    }

    private static long dII(long a, long b, long c, long d, long x, long s, long ac) {
        a += (dI(b, c, d) & 0xFFFFFFFFL) + x + ac;
        a = ((a & 0xFFFFFFFFL) << s) | ((a & 0xFFFFFFFFL) >>> (32 - s));
        a += b;
        return (a & 0xFFFFFFFFL);
    }
}
